// 初始化 WebSocket 连接
const initWebSocket = (currentUsername, socket, messages, route, router) => {
  let uerInfo = localStorage.getItem('userInfo');
  let userInfo = JSON.parse(uerInfo);
  currentUsername.value = userInfo.username;
  socket.value = new WebSocket('ws://localhost:8089/myWs');
  socket.value.onopen = () => {
    console.log('WebSocket 连接成功');
    handleQueryParams(route, messages, socket);
  };
  socket.value.onmessage = async (event) => {
    try {
      const data = JSON.parse(event.data);
      if (data.file) {
        // 如果消息包含文件信息，添加到消息列表
        messages.value.push({
          text: `发送了文件：<a href="${data.file.url}" download="${data.file.name}">${data.file.name}</a>`,
          isUser: false,
          username: data.username,
          isFileMessage: true
        });
      } else if (data.type === 'videoCallRequest') {
        // 接收到视频通话请求
        isVideoCallVisible.value = true;
        isCalling.value = false;
      } else if (data.type === 'answerCall') {
        // 对方接通了视频通话
        callStartTime.value = new Date();
        peerConnection.value = new RTCPeerConnection();
        peerConnection.value.ontrack = (event) => {
          const remoteVideo = document.createElement('video');
          remoteVideo.srcObject = event.streams[0];
          remoteVideo.autoplay = true;
          document.querySelector('.video-call-popup .video-display').appendChild(remoteVideo);
        };
        peerConnection.value.addStream(localStream.value);
        const offer = await peerConnection.value.createOffer();
        await peerConnection.value.setLocalDescription(offer);
        socket.value.send(JSON.stringify({
          type: 'offer',
          offer: offer,
          roomId: roomId.value
        }));
        console.log('对方接通了视频通话');
      } else if (data.type === 'offer') {
        peerConnection.value = new RTCPeerConnection();
        peerConnection.value.ontrack = (event) => {
          const remoteVideo = document.createElement('video');
          remoteVideo.srcObject = event.streams[0];
          remoteVideo.autoplay = true;
          document.querySelector('.video-call-popup .video-display').appendChild(remoteVideo);
        };
        peerConnection.value.addStream(localStream.value);
        await peerConnection.value.setRemoteDescription(new RTCSessionDescription(data.offer));
        const answer = await peerConnection.value.createAnswer();
        await peerConnection.value.setLocalDescription(answer);
        socket.value.send(JSON.stringify({
          type: 'answer',
          answer: answer,
          roomId: roomId.value
        }));
      } else if (data.type === 'answer') {
        await peerConnection.value.setRemoteDescription(new RTCSessionDescription(data.answer));
      } else if (data.type ==='rejectCall') {
        // 对方拒绝了视频通话
        isVideoCallVisible.value = false;
        isCalling.value = false;
        console.log('对方拒绝了视频通话');
      } else if (data.type === 'createRoom') {
        roomId.value = data.roomId;
        console.log(`成功创建房间：${roomId.value}`);
      } else if (data.type === 'joinRoom') {
        roomId.value = data.roomId;
        console.log(`成功加入房间：${roomId.value}`);
      } else {
        messages.value.push({ text: data.message, isUser: false, username: data.username });
      }
    } catch (error) {
      console.error('解析消息时出错:', error);
    }
  };
};

// 处理路由传递过来的 query 参数
const handleQueryParams = (route, messages, socket) => {
  const { username, title, description, mainImageUrl } = route.query;
  console.log(`Query Params: username=${username}, title=${title}, description=${description}, mainImageUrl=${mainImageUrl}`);
  if (username && title && description && mainImageUrl) {
    const message = {
      message: `标题: ${title}, 描述: ${description}, 主图链接: ${mainImageUrl}`,
      isUser: true,
      username: username,
      userid: null,
      userbid: null
    };
    if (socket.value && socket.value.readyState === WebSocket.OPEN) {
      socket.value.send(JSON.stringify(message));
      messages.value.push(message);
    }
  }
};


export { initWebSocket, handleQueryParams };